<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/Apache-2.0
 * @link https://www.gougucms.com
 */
namespace app\admin\model;
use think\model;
use think\facade\Db;
use think\exception;
use Dcat\EasyExcel\Excel;
use Dcat\EasyExcel\Contracts\Sheet as SheetInterface;
use Dcat\EasyExcel\Support\SheetCollection;
class Order extends Model
{
    /**
    * 获取分页列表
    * @param $where
    * @param $param
    */
    public function getOrderList($where, $param)
    {
		$rows = empty($param['limit']) ? get_config('app . page_size') : $param['limit'];
        $order = empty($param['order']) ? 'id desc' : $param['order'];
        $list = self::where($where)
        //->field('id,name,region,specification,produced_time,delivery_time,sorting,sorting_total,out_storage,in_storage,wastage,remark,create_time,sorting_admin,create_admin,delivery_admin,tip,purchaser,order_no,status')
        ->field('o.*,COUNT(o.id) AS total_items,p.name as purchaser,p.phone,p.address,p.user,n.nianji,a.username,f1.name as fenjian1,f2.name as fenjian2')
        ->alias('o')
        ->leftJoin('purchaser p', 'o.purchaser = p.id')
        ->leftJoin('nianji n', 'o.region = n.id')
        ->leftJoin('admin a', 'o.create_admin = a.id')
        ->leftJoin('fenjian f1', 'o.sorting_admin = f1.id')
        ->leftJoin('fenjian f2', 'o.sorting_admin2 = f2.id')
        ->group('o.order_no')
        //->orderRaw("CASE WHEN o.remark IS NOT NULL AND o.remark != '' THEN 0 ELSE 1 END")
        ->order($order) // 保持原有排序规则
        ->paginate($rows, false, ['query' => $param])
        ;
		return $list;
    }

    /**
    * 添加数据
    * @param $param
    */
    public function addOrder($param)
    {
		$insertId = 0;
        try {
			$param['create_time'] = time();
			$insertId = self::strict(false)->field(true)->insertGetId($param);
			add_log('add', $insertId, $param);
        } catch(\Exception $e) {
			return to_assign(1, '操作失败，原因：'.$e->getMessage());
        }
		return to_assign(0,'操作成功',['aid'=>$insertId]);
    }

    /**
    * 编辑信息
    * @param $param
    */
    public function editOrder($param)
    {
        try {
            $param['update_time'] = time();
            $res = self::where('order_no', $param['order_no'])->select();
            $params = [];
            foreach($param as $k=>$v){
                if($k=='id'){

                }else{
                    $params[$k] =$v;
                }
                

            }
            //pr($params);
            
            foreach($res as $key=>$val){
                self::where('id', $val['id'])->strict(false)->field(true)->update($params);
                
            }
            //self::where('order_no', $param['order_no'])->strict(false)->field(true)->update($param);
            //self::where('id', $param['id'])->strict(false)->field(true)->update($param);
			add_log('edit', $param['id'], $param);
        } catch(\Exception $e) {
			return to_assign(1, '操作失败，原因：'.$e->getMessage());
        }
		return to_assign();
    }
	

    /**
    * 根据id获取信息
    * @param $id
    */
    public function getOrderById($id)
    {
        $info = self::where('id', $id)->find();
		return $info;
    }
    /**
    * 根据id获取信息
    * @param $id
    */
    public function getOrderByOrderNo($order_no)
    {
        $info = self::where('order_no', $order_no)->select();
        return $info;
    }
    /**
    * 删除信息
    * @param $id
    * @return array
    */
    public function delOrderById($id,$type=0)
    {
		if($type==0){
			//逻辑删除
			try {
				$param['delete_time'] = time();
				self::where('id', $id)->update(['delete_time'=>time()]);
				add_log('delete', $id);
			} catch(\Exception $e) {
				return to_assign(1, '操作失败，原因：'.$e->getMessage());
			}
		}
		else{
			//物理删除
			try {
				self::where('id', $id)->delete();
				add_log('delete', $id);
			} catch(\Exception $e) {
				return to_assign(1, '操作失败，原因：'.$e->getMessage());
			}
		}
		return to_assign();
    }
    /**
    * excel导入
    * @param $id
    */
    public function excelImport($res){

        $path = $res['filepath'];
        Excel::import('.'.$path)->each(function (SheetInterface $sheet) {
        pr($sheet);
        // 单独处理每个表格内容
        $sheetArray = $sheet->toArray();
        pr($sheetArray);
        $count = $sheet->collect()->count();
        $batch_no = date('YmdHis').rand(100000, 999999);
        
            if($count > 1){
                for ($row = 2;$row <= $count+1; $row++) { 
                    $api = Db::name('Api')->where(['name'=>$sheetArray[$row]['接口']])->value('id');
                    $isp = Db::name('Isp')->where(['name'=>$sheetArray[$row]['运营商']])->value('id');
                    $card_exists = self::where(['iccid'=>$sheetArray[$row]['ICCID']])->count();

                    if($card_exists == 1){
                        continue;
                    }else{
                        $data = [
                            'api_id'    =>   $api,
                            'isp_id'    =>   $isp,
                            'iccid'     =>   $sheetArray[$row]['ICCID'],
                            'msisdn'    =>   $sheetArray[$row]['MSISDN'],
                            'cardnum'   =>   $sheetArray[$row]['MSISDN'],
                            'status'    =>   self::STATUS_TEST_READY,
                            'batch_no'  =>   $batch_no,
                            'create_time' => time()
                        ];
                    
                        $result = self::insert($data);
                        
                        }
                           
                    }             
                }elseif($count == 1){
                    $row = $count + 1;
                    $api = Db::name('Api')->where(['name'=>$sheetArray[$row]['接口']])->value('id');
                    $isp = Db::name('Isp')->where(['name'=>$sheetArray[$row]['运营商']])->value('id');
                    $card_exists = self::where(['iccid'=>$sheetArray[$row]['ICCID']])->count();
                    if($card_exists == 1){
                        
                    }else{
                        $data = [
                            'api_id'    =>   $api,
                            'isp_id'    =>   $isp,
                            'iccid'     =>   $sheetArray[$row]['ICCID'],
                            'msisdn'    =>   $sheetArray[$row]['MSISDN'],
                            'cardnum'   =>   $sheetArray[$row]['MSISDN'],
                            'status'    =>   self::STATUS_TEST_READY,
                            'batch_no'  =>   $batch_no,
                            'create_time' => time()
                        ];

                        $result = self::insert($data);
                        
                    }
                }
                
            
        $keys = $count + 1;
        $last_import = self::where(['iccid'=>$sheetArray[$keys]['ICCID']])->find();

        if(!empty($last_import)){
                $res['count'] = $count;
                return to_assign(0,'导入成功',$res);
            }else{
                return to_assign(1,'导入失败');
            }
         });
    }
}

